﻿//说明
//<input type="text" class="inpall inp435" name="" validateType="*telephone" errorMessage="" confirmMessage="" />
//validateType对应验证类型，加*为必填，为空的话填正则如：/^[0-9]+$/g
//errorMessage错误提示，可选填
//confirmMessage聚焦提示，可选填
//若是带选择性别的输入框，input加上name = "namesex"

function validateInit(inputs) {
    var ipt = $(inputs || "input[validateType]"); //inputs,则获取页面上所有的input
    ipt.focus(function () {
        var meipt = $(this);
        var offset = meipt.attr("validateOffset");
        var pmeipt = meipt.parent();
        pmeipt.css("position", "relative");
        if (offset) {
            offset = offset.toString().split(",");
            if (offset.length == 2) {
                offset = { top: parseInt(offset[0]), left: parseInt(offset[1]) };
            } else {
                offset = { top: 0, left: 0 };
            }
        } else {
            offset = { top: 0, left: 0 };
        }
        //validateOffset=""
        //var etop = 9 + offset.top;//提示ltop
        //var eleft = meipt.width() + 20 + offset.left;//提示left
        var etop = 35 + offset.top;//提示ltop
        var eleft = 10 + offset.left;//提示left
        //if (meipt.attr("validateOffset") == "namesex") {
        //    eleft = eleft + 106;
        //}
        var confirmMsg;//提示文字
        var type = meipt.attr("validateType");//input的validateType值 类型
        var $tips = meipt.data("validate");//取出特定数据中的jquery对象
        if ($tips) $tips.remove();  //如果存在,则 $tips 从页面中删除                 
        $tips = $('<div style="top:' + etop + 'px;left:' + eleft + 'px;"></div>');//创建 新的$tips
        meipt.data("validate", $tips);//将 $tips 存入ipt.data("validate"),以便下次创建时删除
        meipt.removeClass("inperror");//input去掉错误提示样式
        meipt.removeClass("inpconfirm");//input去掉提示样式
        $tips.appendTo(pmeipt);//将提示添加到body  
        if (type.charAt(0) === "*") {
            type = type.substring(1);
        }

        switch (type.toLowerCase()) {
            case "notempty":
                confirmMsg = meipt.attr("confirmMessage") || "请输入!";
                break;
            case "telephone":
                confirmMsg = meipt.attr("confirmMessage") || "请填写手机号!";
                break;
            case "email":
                confirmMsg = meipt.attr("confirmMessage") || "请填写邮箱!";
                break;
            case "num":
                confirmMsg = meipt.attr("confirmMessage") || "请填写数字!";
                break;
            case "chinese":
                confirmMsg = meipt.attr("confirmMessage") || "请填写中文!";
                break;
            case "letter":
                confirmMsg = meipt.attr("confirmMessage") || "请填写数母!";
                break;
            case "idcard":
                confirmMsg = meipt.attr("confirmMessage") || "请填写身份证号!";
                break;
            case "number":
                confirmMsg = meipt.attr("confirmMessage") || "请填写数字(如:1)";
                break;
            case "arithmetic":
                confirmMsg = meipt.attr("confirmMessage") || "请填写正确(如:20.12)!";
                break;
            default:
                confirmMsg = meipt.attr("confirmMessage") || "请填写!";
                break;
        }
        if (confirmMsg) {
            $tips.html(confirmMsg).addClass("validate_confirm_info");
            meipt.addClass("inpconfirm");
            return false;
        }
    })
}

function validate(inputs, b) {
    var ipt = $(inputs || "input[validateType]"); //inputs,则获取页面上所有的input

    //  alert(ipt.is("[validateType]"));
    if (ipt.length > 1) {//如果待处理元素超过1个,则循环处理
        var result = true;
        for (var i = 0; i < ipt.length; i++) {
            if (!validate(ipt[i])) { //取出一个独立的元素递归
                result = false;
                if (b) {
                    return result;
                }
            }
        }
        return result;
    }
    if (!ipt.is("[validateType]")) {
        return true;
    }
    var offset = ipt.attr("validateOffset");
    if (offset) {
        offset = offset.toString().split(",");
        if (offset.length == 2) {
            offset = { top: parseInt(offset[0]), left: parseInt(offset[1]) };
        } else {
            offset = { top: 0, left: 0 };
        }
    } else {
        offset = { top: 0, left: 0 };
    }
    //validateOffset=""
    var pmeipt = ipt.parent();
    pmeipt.css("position", "relative");
    //var etop = 9 + offset.top;//提示ltop
    //var eleft = meipt.width() + 20 + offset.left;//提示left
    var etop = 35 + offset.top;//提示ltop
    var eleft = 10 + offset.left;//提示left
    var errorMsg;//错误提示文字
    var type = ipt.attr("validateType");//input的validateType值 类型
    var $tips = ipt.data("validate");//取出特定数据中的jquery对象
    if ($tips) $tips.remove();  //如果存在,则 $tips 从页面中删除         
    $tips = $('<div style="top:' + etop + 'px;left:' + eleft + 'px;"></div>');//创建 新的$tips
    ipt.data("validate", $tips);//将 $tips 存入ipt.data("validate"),以便下次创建时删除
    ipt.removeClass("inpconfirm");//input去掉提示样式
    ipt.removeClass("inperror");//input去掉错误提示样式
    $tips.appendTo(pmeipt);//将提示添加到body  

    if (type && type.charAt(0) === "*") {
        type = type.substring(1);
    } else { //允许空
        if ($.trim(ipt.val()) == "") {
            return true;
        }
    }
    // 侯涛添加，点击提示信息时使文本框得到焦点。
    $tips.click(function () {
        $(ipt).focus();
    });

    var types = type.split(' ');
    switch (types[0].toLowerCase()) {
        case "notempty":
            if ($.trim(ipt.val()) == "") {
                // 侯涛添加，增加自定义为空提示信息。
                var tipMsg = $(ipt).attr("tipMsg");
                if (tipMsg) {
                    errorMsg = tipMsg;
                } else {
                    errorMsg = "不能为空!";
                }
            }
            else {
                if (types.length > 1 && types[1].toLowerCase() === "defined") {
                    errorMsg = defineValidata(ipt);
                }
            }
            break;
        case "telephone":
            if (/^[\d]{11}$/.test(ipt.val()) == false) {
                errorMsg = ipt.attr("errorMessage") || "请填写正确的手机号!";
            } else {
                if (types.length > 1 && types[1].toLowerCase() === "defined") {
                    errorMsg = defineValidata(ipt);
                }
            }
            break;
        case "email":
            if (/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/.test(ipt.val()) == false) {
                errorMsg = ipt.attr("errorMessage") || "请填写正确的邮箱!";
            } else {
                if (types.length > 1 && types[1].toLowerCase() === "defined") {
                    errorMsg = defineValidata(ipt);
                }
            }
            break;
        case "num":
            //  /^\d+(\.\d+)?$/   ----验证只能是文字跟小数点     /^\d+(\.\d{2})?$/   只能是数字 保留小数点后2位    /^[0-9]+$/   只能是数字
            if (/^\d+(\.\d+)?$/.test(ipt.val()) == false) {
                errorMsg = ipt.attr("errorMessage") || "请填写数字!";
            } else {
                if (types.length > 1 && types[1].toLowerCase() === "defined") {
                    errorMsg = defineValidata(ipt);
                }
            }
            break;
        case "chinese":
            if (/^[\u4e00-\u9fa5]+$/.test(ipt.val()) == false) {
                errorMsg = ipt.attr("errorMessage") || "请填写中文!";
            } else {
                if (types.length > 1 && types[1].toLowerCase() === "defined") {
                    errorMsg = defineValidata(ipt);
                }
            }
            break;
        case "letter":
            if (/^[A-Za-z]+$/.test(ipt.val()) == false) {
                errorMsg = ipt.attr("errorMessage") || "请填写数母!";
            } else {
                if (types.length > 1 && types[1].toLowerCase() === "defined") {
                    errorMsg = defineValidata(ipt);
                }
            }
            break;
        case "idcard":
            if (!isIdCardNo(ipt.val())) {
                errorMsg = ipt.attr("errorMessage") || carerrorStr;
            } else {
                if (types.length > 1 && types[1].toLowerCase() === "defined") {
                    errorMsg = defineValidata(ipt);
                }
            }
            break;
        case "number":
            //  /^\d+(\.\d+)?$/   ----验证只能是文字跟小数点     /^\d+(\.\d{2})?$/   只能是数字 保留小数点后2位    /^[0-9]+$/   只能是数字
            if (/^[0-9]+$/.test(ipt.val()) == false) {
                errorMsg = ipt.attr("errorMessage") || "请填写数字(如:1)";
            } else {
                if (types.length > 1 && types[1].toLowerCase() === "defined") {
                    errorMsg = defineValidata(ipt);
                }
            }
            break;
        case "arithmetic":
            if (/^\d+(\.\d+)?$/.test(ipt.val()) == false) {
                errorMsg = ipt.attr("errorMessage") || "请填写正确(如:20.12)!";
            } else {
                if (types.length > 1 && types[1].toLowerCase() === "defined") {
                    errorMsg = defineValidata(ipt);
                }
            }
            break;
        default:
            try {
                var regex = eval(type);
                if (regex.constructor === RegExp) {
                    if (regex.test(ipt.val()) == false) {
                        errorMsg = ipt.attr("errorMessage") || "验证失败!";
                    }
                }
            } catch (e) {

            }
            break;
    }

    // 侯涛添加，增加长度限制提示
    var limitlength = $(ipt).attr("limitlength");

    if (limitlength) {
        var length = parseInt(limitlength);

        if (!isNaN(length)) {
            if ($(ipt)[0].value.length != length) {
                var limitmsg = $(ipt).attr("limitmsg");

                if (limitmsg) {
                    errorMsg = limitmsg;
                } else {
                    errorMsg = "长度只能为" + length + "位";
                }
            }
        }
    }


    var ajaxurl = $(ipt).attr("ajaxurl");
    if (ajaxurl) {
        $.ajax({
            type: "post",
            url: $.TransactionURL() + ajaxurl,
            cache: false,
            async: false,
            success: function (xmlobj) {
                if (xmlobj.Code == 0) {
                    if (xmlobj.Data.status == "n") {
                        errorMsg = xmlobj.Data.info;
                    }
                } else {
                    kk.popup(xmlobj.Message, "err");
                }
            }
        });
    }

    var customererr = $(ipt).attr("customererr");
    if (customererr) {
        errorMsg = customererr;
    }

    if (errorMsg) {
        $tips.html(errorMsg).addClass("validate_error_info");
        ipt.addClass("inperror");
        return false;
    }
    $tips.addClass("validate_right");
    return true;
}

function defineValidata(obj) {
    var str = $(obj).attr("data_option");
    if (str != undefined) {
        jsObj = eval('({' + str + '})');
        if (jsObj.onBtnclick && jsObj.onBtnclick instanceof Function) {
            var msg = jsObj.onBtnclick($(obj));
            if (msg) {
                return msg;
            }
        }
    }
}

var carerrorStr = "请填写身份证号码!";

//--身份证号码验证-支持新的带x身份证
function isIdCardNo(num) {
    if (num != "") {
        var factorArr = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1);
        var varArray = new Array();
        var intValue;
        var lngProduct = 0;
        var intCheckDigit;
        var intStrLen = num.length;
        var idNumber = num;
        // initialize
        if ((intStrLen != 15) && (intStrLen != 18)) {
            carerrorStr = "输入身份证号码长度不对！";
            return false;
        }
        // check and set value
        for (i = 0; i < intStrLen; i++) {
            varArray[i] = idNumber.charAt(i);
            if ((varArray[i] < '0' || varArray[i] > '9') && (i != 17)) {
                carerrorStr = "错误的身份证号码！";
                return false;
            } else if (i < 17) {
                varArray[i] = varArray[i] * factorArr[i];
            }
        }
        if (intStrLen == 18) {
            //check date
            var yyyy = idNumber.substring(6, 10);
            if (yyyy > 2200 || yyyy < 1900) {
                carerrorStr = "输入身份证号,年度非法！";
                return false;
            }

            var mm = idNumber.substring(10, 12);
            if (mm > 12 || mm <= 0) {
                carerrorStr = "输入身份证号,月份非法！";
                return false;
            }

            var dd = idNumber.substring(12, 14);
            if (dd > 31 || dd <= 0) {
                carerrorStr = "输入身份证号,日期非法！";
                return false;
            }

            // calculate the sum of the products
            for (i = 0; i < 17; i++) {
                lngProduct = lngProduct + varArray[i];
            }
            // calculate the check digit
            intCheckDigit = 12 - lngProduct % 11;
            switch (intCheckDigit) {
                case 10:
                    intCheckDigit = 'X';
                    break;
                case 11:
                    intCheckDigit = 0;
                    break;
                case 12:
                    intCheckDigit = 1;
                    break;
            }
            // check last digit
            if (varArray[17].toUpperCase() != intCheckDigit) {
                carerrorStr = "身份证效验位错误！";
                return false;
            }
        }
        else {
            //length is 15
            //check date
            var yyyy = "19" + idNumber.substring(6, 8);
            var mm = idNumber.substring(8, 10);
            var dd = idNumber.substring(10, 12);

            if (mm > 12 || mm <= 0) {
                carerrorStr = "输入身份证号,月份非法！";
                return false;
            }

            if (dd > 31 || dd <= 0) {
                carerrorStr = "输入身份证号,日期非法！";
                return false;
            }
        }
        return true;
    }
    return false;
}

function ValidInit() {
    var bodyobj = $("body");
    if (bodyobj.find("form").length > 0) {
        if (bodyobj.find("form").find("input[validateType]").length > 0) {
            bodyobj.find("form").find("input[validateType]").blur(function () {
                validate($(this));
            })
        }
    }
}

$(function () {
    ValidInit();
})

